package com.fenda.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by huanggc on 2019/11/7.
 */
public class ReflectDemo2 {
    public static void main(String[] args) {
        /*Student s = new Student();*/
        try {
            Class clazz = Class.forName("com.fenda.reflect.Student");
            //class直接newInstance等于调用了空构造器的newInstance
            Object o = clazz.newInstance();//空Student
            //用field来给name设值为秦弘
            Field o2 = clazz.getDeclaredField("name");
            o2.setAccessible(true);//让安全校验通过
            o2.set(o,"秦弘");
            System.out.println(o);
            try {
                Method setAge = clazz.getDeclaredMethod("setAge", int.class);
                setAge.invoke(o,18);
                System.out.println(o);

                Method setLength = clazz.getDeclaredMethod("setLength", int.class);
                setLength.invoke(o,2);
                System.out.println(o);

                Field length = clazz.getDeclaredField("length");
                length.setAccessible(true);
                length.set(o,3);
                System.out.println(o);

                Method chifan = clazz.getDeclaredMethod("chifan", String.class, int.class);
                chifan.invoke(o,"海鲜大餐",200);

                Method chifan1 = clazz.getDeclaredMethod("chifan", String.class);
                chifan1.invoke(o,"KFC");

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            //用Method来给age赋值为18 setAge



        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
